<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品详情 - 商品竞品分析系统</title>
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
    <!-- Fancybox CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.css">
    <!-- Dropzone CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/min/dropzone.min.css">
    <style>
        :root {
            --primary-color: #6a5acd; /* 柔和的紫色 */
            --primary-dark: #5d4ebd;
            --secondary-color: #ff7eb3; /* 可爱的粉色 */
            --light-color: #f8f9fa;
            --dark-color: #4a4a69; /* 柔和的深色 */
            --success-color: #7fd8be; /* 柔和的绿色 */
            --warning-color: #ffdb7d; /* 柔和的黄色 */
            --danger-color: #ff7d94;  /* 柔和的红色 */
            --info-color: #77c0fd;    /* 柔和的蓝色 */
            --font-primary: 'Nunito', 'Segoe UI', sans-serif;
            --border-radius-lg: 16px;
            --border-radius-md: 12px;
            --border-radius-sm: 8px;
            --shadow-default: 0 4px 15px rgba(0, 0, 0, 0.05);
            --shadow-hover: 0 8px 25px rgba(0, 0, 0, 0.08);
            --transition-default: all 0.3s ease;
        }
        body {
            background-color: #f5f8ff;
            color: var(--dark-color);
            font-family: var(--font-primary);
            line-height: 1.6;
        }
        .banner {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 2.8rem 0;
            margin-bottom: 2.5rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border-radius: 0 0 28px 28px;
            position: relative;
            overflow: hidden;
        }
        .banner::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -10%;
            width: 120%;
            height: 200%;
            background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 100%);
            transform: rotate(-15deg);
            pointer-events: none;
        }
        .banner h1 {
            font-weight: 700;
            margin-bottom: 0.5rem;
            font-size: 2.2rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .banner .lead {
            opacity: 0.9;
            margin-bottom: 0;
        }
        .card {
            border: none;
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow-default);
            margin-bottom: 2rem;
            transition: var(--transition-default);
            overflow: hidden;
        }
        .card:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-3px);
        }
        .card-header {
            background-color: white;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            font-weight: 600;
            padding: 1.25rem 1.5rem;
            display: flex;
            align-items: center;
        }
        .card-header i {
            margin-right: 0.75rem;
            color: var(--primary-color);
            font-size: 1.1rem;
        }
        .card-body {
            padding: 1.5rem;
        }
        
        /* 图片网格样式 */
        .product-images {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 1rem;
        }
        .product-image-item {
            position: relative;
            aspect-ratio: 1/1;
            overflow: hidden;
            border-radius: var(--border-radius-md);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
            transition: var(--transition-default);
            cursor: pointer;
        }
        .product-image-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
        }
        .product-image-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s ease;
        }
        .product-image-item:hover img {
            transform: scale(1.08);
        }
        .image-actions {
            position: absolute;
            top: 0;
            right: 0;
            display: flex;
            gap: 5px;
            padding: 8px;
            opacity: 0;
            transition: opacity 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 0 0 0 12px;
        }
        .product-image-item:hover .image-actions {
            opacity: 1;
        }
        .btn-image-action {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-size: 14px;
            padding: 0;
            background: white;
            border: none;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            color: var(--dark-color);
            transition: all 0.3s ease;
        }
        .btn-image-action:hover {
            transform: scale(1.15);
        }
        .btn-image-delete {
            color: var(--danger-color);
        }
        .btn-image-view {
            color: var(--primary-color);
        }
        .btn-image-extract {
            color: var(--success-color);
        }
        .image-status {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 5px 8px;
            font-size: 12px;
            background: rgba(255, 255, 255, 0.9);
            text-align: center;
            transition: transform 0.3s ease;
            transform: translateY(100%);
        }
        .image-status.has-text {
            color: var(--success-color);
        }
        .image-status.no-text {
            color: var(--warning-color);
        }
        .product-image-item:hover .image-status {
            transform: translateY(0);
        }
        
        /* 分析结果样式优化 */
        .analysis-result {
            font-size: 0.95rem;
            line-height: 1.6;
            color: var(--dark-color);
            padding: 1.5rem;
            background: white;
            border-radius: var(--border-radius-md);
            box-shadow: var(--shadow-default);
        }
        .analysis-result h1, 
        .analysis-result h2, 
        .analysis-result h3 {
            font-weight: 700;
            color: var(--primary-color);
            margin-top: 1.3rem;
            margin-bottom: 0.8rem;
            font-size: 1.25rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid rgba(106, 90, 205, 0.1);
        }
        .analysis-result h4, 
        .analysis-result h5, 
        .analysis-result h6 {
            font-weight: 600;
            color: var(--secondary-color);
            margin-top: 1rem;
            margin-bottom: 0.6rem;
            font-size: 1.1rem;
        }
        .analysis-result p {
            margin-bottom: 1rem;
        }
        .analysis-result ul, 
        .analysis-result ol {
            padding-left: 1.3rem;
            margin-bottom: 1rem;
        }
        .analysis-result li {
            margin-bottom: 0.4rem;
        }
        .analysis-result blockquote {
            padding: 0.5rem 1rem;
            margin-bottom: 1rem;
            background-color: rgba(106, 90, 205, 0.05);
            border-left: 3px solid var(--primary-color);
            color: #666;
        }
        .highlight {
            background-image: linear-gradient(120deg, rgba(255, 223, 235, 0.6) 0%, rgba(255, 223, 235, 0.3) 100%);
            padding: 0 0.2rem;
            border-radius: 3px;
            color: var(--secondary-color);
            font-weight: 600;
            display: inline-block;
        }
        
        /* 统计卡片样式优化 */
        .stats-row {
            margin-bottom: 2rem;
        }
        .stat-card {
            text-align: center;
            padding: 1.2rem;
            background-color: white;
            border-radius: var(--border-radius-md);
            box-shadow: var(--shadow-default);
            margin-bottom: 1rem;
            transition: var(--transition-default);
            border-top: 4px solid transparent;
        }
        .stat-card:nth-child(1) {
            border-top-color: var(--primary-color);
        }
        .stat-card:nth-child(2) {
            border-top-color: var(--success-color);
        }
        .stat-card:nth-child(3) {
            border-top-color: var(--secondary-color);
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-hover);
        }
        .stat-number {
            font-size: 2.2rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 0.6rem;
            line-height: 1;
        }
        .stat-label {
            color: #9e9eb3;
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        
        /* 按钮样式优化 */
        .btn {
            border-radius: var(--border-radius-sm);
            font-weight: 600;
            padding: 0.6rem 1.25rem;
            transition: var(--transition-default);
            letter-spacing: 0.02em;
        }
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        .btn-primary:hover, .btn-primary:focus {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(106, 90, 205, 0.3);
        }
        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
            color: white;
        }
        .btn-success:hover {
            background-color: #6dcbae;
            border-color: #6dcbae;
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(127, 216, 190, 0.3);
        }
        .btn-analyze {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            font-weight: 600;
            padding: 0.8rem 1.5rem;
            color: white;
            border-radius: 50px;
        }
        .btn-analyze:hover {
            background-color: #ff6ba5;
            border-color: #ff6ba5;
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 126, 179, 0.3);
        }
        .btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.85rem;
        }
        .btn-icon {
            display: inline-flex;
            align-items: center;
        }
        .btn-icon i {
            margin-right: 0.5rem;
        }
        
        /* 进度指示器 */
        .extract-progress {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background-color: rgba(0,0,0,0.1);
            overflow: hidden;
            transform: scaleX(0);
            transform-origin: left;
            transition: transform 0.3s ease;
        }
        .extract-progress.active {
            transform: scaleX(1);
        }
        .extract-progress::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--success-color);
            animation: progressAnimation 2s ease infinite;
        }
        @keyframes progressAnimation {
            0% {
                transform: translateX(-100%);
            }
            50% {
                transform: translateX(30%);
            }
            100% {
                transform: translateX(100%);
            }
        }
        
        /* 确认对话框样式 */
        .confirm-dialog {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1050;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .confirm-dialog.show {
            opacity: 1;
            visibility: visible;
        }
        .confirm-dialog-content {
            background: white;
            border-radius: 16px;
            width: 90%;
            max-width: 350px;
            padding: 1.5rem;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            transform: translateY(20px);
            transition: transform 0.3s ease;
        }
        .confirm-dialog.show .confirm-dialog-content {
            transform: translateY(0);
        }
        .confirm-dialog-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: var(--dark-color);
        }
        .confirm-dialog-message {
            margin-bottom: 1.5rem;
            color: #777;
            font-size: 0.95rem;
        }
        .confirm-dialog-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        /* 加载动画和无内容占位符 */
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 2rem;
        }
        .loading-spinner .spinner-border {
            width: 3rem;
            height: 3rem;
            color: var(--primary-color);
        }
        .no-content-placeholder {
            background-color: #f8f9fa;
            border-radius: 16px;
            padding: 3rem 2rem;
            text-align: center;
        }
        .no-content-placeholder i {
            font-size: 3rem;
            color: #d8dae5;
            margin-bottom: 1.5rem;
        }
        .no-content-placeholder h5 {
            font-size: 1.2rem;
            color: var(--dark-color);
            margin-bottom: 0.8rem;
        }
        .no-content-placeholder p {
            color: #9e9eb3;
            margin-bottom: 1.5rem;
        }
        
        /* Fancybox自定义样式 */
        .fancybox__toolbar {
            --f-button-color: var(--primary-color);
            --f-button-hover-bg: rgba(106, 90, 205, 0.1);
        }
        .fancybox__caption {
            font-family: var(--font-primary);
        }
        
        /* Toast通知样式 */
        .toast-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            width: 320px;
            background: white;
            border-radius: var(--border-radius-md);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
            padding: 15px;
            display: flex;
            align-items: flex-start;
            z-index: 1060;
            transform: translateX(400px);
            opacity: 0;
            transition: all 0.3s ease;
        }
        .toast-notification.show {
            transform: translateX(0);
            opacity: 1;
        }
        .toast-success {
            border-left: 4px solid var(--success-color);
        }
        .toast-error {
            border-left: 4px solid var(--danger-color);
        }
        .toast-info {
            border-left: 4px solid var(--info-color);
        }
        .toast-icon {
            margin-right: 15px;
            font-size: 22px;
        }
        .toast-success .toast-icon {
            color: var(--success-color);
        }
        .toast-error .toast-icon {
            color: var(--danger-color);
        }
        .toast-info .toast-icon {
            color: var(--info-color);
        }
        .toast-content {
            flex: 1;
        }
        .toast-title {
            font-weight: 600;
            margin-bottom: 5px;
            color: var(--dark-color);
        }
        .toast-message {
            font-size: 0.9rem;
            color: #666;
        }
        .toast-close {
            border: none;
            background: transparent;
            font-size: 16px;
            color: #aaa;
            cursor: pointer;
            padding: 0;
            margin-left: 10px;
        }
        .toast-close:hover {
            color: #666;
        }
        
        /* 添加上传进度样式 */
        .upload-progress-container {
            position: fixed;
            top: 20px;
            right: 20px;
            width: 300px;
            z-index: 1050;
        }
        
        .upload-progress-item {
            background: white;
            border-radius: var(--border-radius-md);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            margin-bottom: 10px;
            padding: 15px;
            transform: translateX(120%);
            transition: transform 0.3s ease;
            border-left: 4px solid var(--primary-color);
        }
        
        .upload-progress-item.show {
            transform: translateX(0);
        }
        
        .upload-progress-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .upload-progress-title {
            font-weight: 600;
            color: var(--dark-color);
            font-size: 0.9rem;
        }
        
        .upload-progress-status {
            font-size: 0.8rem;
            color: var(--primary-color);
        }
        
        .upload-progress-bar {
            height: 4px;
            background: #eee;
            border-radius: 2px;
            overflow: hidden;
        }
        
        .upload-progress-bar-inner {
            height: 100%;
            background: var(--primary-color);
            width: 0;
            transition: width 0.3s ease;
        }
        
        .upload-progress-item.success {
            border-left-color: var(--success-color);
        }
        
        .upload-progress-item.error {
            border-left-color: var(--danger-color);
        }
        
        /* Dropzone 样式优化 */
        .dropzone {
            border: 2px dashed var(--primary-color);
            border-radius: var(--border-radius-lg);
            background: rgba(106, 90, 205, 0.02);
            transition: all 0.3s ease;
        }
        
        .dropzone:hover {
            background: rgba(106, 90, 205, 0.05);
        }
        
        .dropzone.dz-drag-hover {
            border-color: var(--secondary-color);
            background: rgba(255, 126, 179, 0.05);
        }
        
        .dz-preview {
            position: relative;
            margin: 10px;
        }
        
        .dz-image {
            border-radius: var(--border-radius-md);
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .dz-success-mark, .dz-error-mark {
            background: white;
            border-radius: 50%;
            padding: 5px;
            position: absolute;
            top: -10px;
            right: -10px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }
        
        .dz-success-mark {
            color: var(--success-color);
        }
        
        .dz-error-mark {
            color: var(--danger-color);
        }
    </style>
</head>
<body>
    <!-- 顶部Banner -->
    <div class="banner">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 id="productName">产品详情</h1>
                    <p class="lead" id="productDescription">加载中...</p>
                </div>
                <div class="col-md-4 text-end">
                    <a href="/" class="btn btn-light btn-lg">
                        <i class="fas fa-home"></i> 返回首页
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container mb-5">
        <!-- 状态指标行 -->
        <div class="row mb-4" id="statRow">
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-number" id="imageCountStat">-</div>
                    <div class="stat-label">图片数量</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-number" id="analysisStatusStat">-</div>
                    <div class="stat-label">分析状态</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-number" id="creationDateStat">-</div>
                    <div class="stat-label">创建日期</div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <!-- 左侧边栏 -->
            <div class="col-lg-4">
                <!-- 操作卡片 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="fas fa-cogs"></i> 产品操作
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-3">
                            <button id="analyzeProductBtn" class="btn btn-primary btn-analyze">
                                <i class="fas fa-chart-bar"></i> 开始分析
                            </button>
                            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadModal">
                                <i class="fas fa-upload"></i> 上传图片
                            </button>
                            <a href="/wordcloud" class="btn btn-secondary">
                                <i class="fas fa-cloud"></i> 词云分析
                            </a>
                            <a href="/" class="btn btn-outline-primary">
                                <i class="fas fa-list"></i> 查看所有产品
                            </a>
                            <a href="/chat" class="btn btn-primary ms-2">
                                <i class="fas fa-comment-dots me-1"></i> 询问AI助手
                            </a>
                        </div>
                    </div>
                </div>
                
                <!-- 产品信息卡片 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-info-circle"></i> 产品信息
                    </div>
                    <div class="card-body">
                        <div class="mb-3" id="productInfo">
                            <p><strong>产品名称：</strong> <span id="productNameInfo">加载中...</span></p>
                            <p><strong>创建时间：</strong> <span id="productDate">加载中...</span></p>
                            <p><strong>图片数量：</strong> <span id="imageCount">加载中...</span></p>
                            <p><strong>分析状态：</strong> <span id="analysisStatus">加载中...</span></p>
                        </div>
                    </div>
                </div>

                <!-- 文件上传区域 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">上传文件</h5>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">选择文件</label>
                                <input type="file" class="form-control" id="fileInput" multiple 
                                       accept=".png,.jpg,.jpeg,.gif,.bmp,.webp,.pdf,.docx,.doc,.xlsx,.xls,.csv,.txt,.md,.json,.yaml,.yml">
                                <div class="form-text">
                                    支持的文件类型：图片(.png,.jpg,.jpeg,.gif,.bmp,.webp)、
                                    文档(.pdf,.docx,.doc)、表格(.xlsx,.xls,.csv)、
                                    文本(.txt,.md)、配置(.json,.yaml,.yml)
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload me-2"></i>上传文件
                            </button>
                        </form>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">文件列表</h5>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-secondary" id="refreshFiles">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>文件名</th>
                                        <th>类型</th>
                                        <th>大小</th>
                                        <th>上传时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="fileList">
                                    <!-- 文件列表将通过JS动态插入 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧主内容 -->
            <div class="col-lg-8">
                <!-- 图片展示卡片 -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-images"></i> 产品图片
                        </div>
                        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">
                            <i class="fas fa-plus"></i> 添加图片
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="noImages" class="no-content-placeholder" style="display: none;">
                            <i class="fas fa-image fa-3x mb-3 text-muted"></i>
                            <h5>暂无图片</h5>
                            <p class="text-muted">请先上传产品相关图片进行分析</p>
                            <button class="btn btn-primary mt-3" data-bs-toggle="modal" data-bs-target="#uploadModal">
                                <i class="fas fa-upload"></i> 上传图片
                            </button>
                        </div>
                        <div class="product-images" id="productImages">
                            <!-- 图片会动态加载到这里 -->
                        </div>
                    </div>
                </div>
                
                <!-- 分析结果卡片 -->
                <div class="card" id="analysisResultCard">
                    <div class="card-header">
                        <i class="fas fa-chart-bar"></i> 竞品分析结果
                    </div>
                    <div class="card-body">
                        <div id="noAnalysisResult" class="no-content-placeholder">
                            <i class="fas fa-chart-bar fa-3x mb-3 text-muted"></i>
                            <h5>暂无分析结果</h5>
                            <p class="text-muted">上传产品图片后，点击"开始分析"按钮进行智能分析</p>
                            <button id="startAnalysisBtn" class="btn btn-primary mt-3">
                                <i class="fas fa-chart-bar"></i> 开始分析
                            </button>
                        </div>
                        <div id="analysisLoading" class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-3" id="analysisLoadingText">正在进行智能分析，这可能需要1-2分钟时间...</p>
                            <div class="progress mt-3">
                                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                            </div>
                            <p class="mt-2 text-muted small" id="analysisLoadingStatus">正在准备分析...</p>
                        </div>
                        <div id="analysisResult" class="analysis-result" style="display: none;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 上传图片模态框 -->
    <div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadModalLabel">上传产品图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted mb-3">上传产品相关的图片，支持JPG、PNG格式。清晰的产品图片和参数信息有助于更准确的分析。</p>
                    
                    <!-- 简单的文件上传表单 -->
                    <form id="simpleUploadForm">
                        <input type="hidden" id="productIdInput" value="{{ product_id }}">
                        <div class="mb-3">
                            <label for="modalFileInput" class="form-label">选择图片文件</label>
                            <input type="file" class="form-control" id="modalFileInput" name="files" accept="image/jpeg,image/png,image/jpg" multiple>
                            <div class="form-text">支持JPG、PNG格式，可以一次选择多个文件</div>
                        </div>
                    </form>
                    
                    <!-- 上传进度显示 -->
                    <div id="uploadProgress" class="progress mt-3" style="display: none;">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="uploadStatus" class="mt-2 small text-muted"></div>
                    
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-info-circle"></i> 
                        提示：可以一次上传多张图片
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" id="uploadImagesBtn" class="btn btn-primary">
                        <i class="fas fa-upload"></i> 开始上传
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 文件预览模态框 -->
    <div class="modal fade" id="filePreviewModal" tabindex="-1" aria-labelledby="filePreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="filePreviewModalLabel">文件预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 图片预览 -->
                    <div id="imagePreview" class="d-none">
                        <img src="" class="img-fluid" alt="图片预览">
                    </div>
                    
                    <!-- PDF预览 -->
                    <div id="pdfPreview" class="d-none">
                        <iframe src="" width="100%" height="600px" frameborder="0"></iframe>
                    </div>
                    
                    <!-- Word文档预览 -->
                    <div id="docxPreview" class="d-none">
                        <div class="docx-content"></div>
                    </div>
                    
                    <!-- Excel预览 -->
                    <div id="excelPreview" class="d-none">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <tbody id="excelContent"></tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- 文本内容预览 -->
                    <div id="textPreview" class="d-none">
                        <pre class="text-content"></pre>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Fancybox JS -->
    <script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.umd.js"></script>
    <!-- Dropzone JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/min/dropzone.min.js"></script>
    <!-- Marked - Markdown parser -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- 添加上传处理脚本 -->
    <script src="/static/temp/upload.js"></script>
    <script>
        // 全局变量
        const productId = '{{ product_id }}';
        let productData = null;
        let myDropzone;
        
        // 初始化Dropzone
        Dropzone.autoDiscover = false;
        
        // 页面加载时获取产品详情
        document.addEventListener('DOMContentLoaded', async function() {
            if (!productId) {
                window.location.href = '/';
                return;
            }
            
            // 设置全局productId供上传脚本使用
            window.productId = productId;
            
            // 加载产品详情
            await loadProductDetails();
            
            // 分析按钮事件处理
            document.getElementById('analyzeProductBtn').addEventListener('click', analyzeProduct);
            document.getElementById('startAnalysisBtn').addEventListener('click', analyzeProduct);
            
            // 初始化上传模态框事件
            document.getElementById('uploadModal').addEventListener('hidden.bs.modal', function () {
                document.getElementById('simpleUploadForm').reset();
                document.getElementById('uploadProgress').style.display = 'none';
                const progressBar = document.querySelector('#uploadProgress .progress-bar');
                progressBar.style.width = '0%';
                progressBar.classList.remove('bg-success', 'bg-danger');
                document.getElementById('uploadStatus').textContent = '';
                
                // 清除文件预览
                const filePreview = document.querySelector('.file-preview');
                if (filePreview) {
                    filePreview.style.display = 'none';
                    filePreview.innerHTML = '';
                }
                
                document.getElementById('uploadImagesBtn').disabled = false;
                document.getElementById('uploadImagesBtn').innerHTML = '<i class="fas fa-upload"></i> 开始上传';
            });

            // 添加额外的Fancybox初始化，防止之前的初始化失败
            setTimeout(function() {
                try {
                    console.log("尝试重新初始化Fancybox...");
                    // 重新初始化一次Fancybox
                    Fancybox.bind('[data-fancybox="gallery"]', {
                        loop: true,
                        Toolbar: {
                            display: [
                                "zoom",
                                "slideShow", 
                                "fullScreen", 
                                "download", 
                                "close"
                            ]
                        }
                    });
                    console.log("Fancybox重新初始化成功");
                } catch(e) {
                    console.error("Fancybox重新初始化失败:", e);
                }
            }, 1000); // 延迟1秒执行，确保所有元素都已加载
        });
        
        // 分析产品函数
        async function analyzeProduct() {
            if (!productData || productData.images.length === 0) {
                alert('请先上传图片');
                return;
            }
            
            try {
                // 显示加载中
                document.getElementById('noAnalysisResult').style.display = 'none';
                document.getElementById('analysisResult').style.display = 'none';
                document.getElementById('analysisLoading').style.display = 'block';
                
                // 禁用按钮
                const analyzeButtons = document.querySelectorAll('#analyzeProductBtn, #startAnalysisBtn');
                analyzeButtons.forEach(btn => {
                    btn.disabled = true;
                    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 分析中...';
                });
                
                // 发送分析请求
                const response = await fetch(`/api/products/${productId}/analyze`, {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error('分析请求失败');
                }
                
                const result = await response.json();
                showToast('分析中', '分析任务已启动，正在处理...', 'info');
                
                // 开始轮询检查分析结果
                await pollAnalysisResult();
                
            } catch (error) {
                console.error('分析失败:', error);
                showToast('分析失败', '请重试', 'error');
                
                // 隐藏加载中，显示无结果
                document.getElementById('analysisLoading').style.display = 'none';
                document.getElementById('noAnalysisResult').style.display = 'block';
                
                // 重新启用按钮
                const analyzeButtons = document.querySelectorAll('#analyzeProductBtn, #startAnalysisBtn');
                analyzeButtons.forEach(btn => {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-chart-bar"></i> 开始分析';
                });
            }
        }
        
        // 轮询检查分析结果
        async function pollAnalysisResult() {
            const maxAttempts = 30; // 最多尝试30次，大约5分钟
            const pollingInterval = 10000; // 10秒轮询一次
            let attempts = 0;
            
            // 加载状态提示文本
            const loadingMessages = [
                "正在提取图片文本内容...",
                "正在分析产品特性...",
                "正在分析竞品优势...",
                "正在比较市场定位...",
                "正在生成详细报告...",
                "正在优化分析结果...",
                "即将完成分析..."
            ];
            
            return new Promise((resolve, reject) => {
                const checkResult = async () => {
                    try {
                        // 获取产品详情
                        const response = await fetch(`/api/products/${productId}`);
                        
                        if (!response.ok) {
                            throw new Error('获取产品详情失败');
                        }
                        
                        const product = await response.json();
                        
                        // 检查是否有分析结果
                        if (product.analysis_result) {
                            // 分析完成，显示结果
                            document.getElementById('analysisLoading').style.display = 'none';
                            document.getElementById('analysisResult').style.display = 'block';
                            document.getElementById('analysisResult').innerHTML = formatAnalysisResult(product.analysis_result);
                            
                            // 更新产品数据
                            productData = product;
                            
                            // 更新分析状态
                            updateAnalysisStatus(true);
                            
                            // 重新启用按钮
                            const analyzeButtons = document.querySelectorAll('#analyzeProductBtn, #startAnalysisBtn');
                            analyzeButtons.forEach(btn => {
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fas fa-chart-bar"></i> 重新分析';
                            });
                            
                            showToast('分析完成', '产品分析已完成', 'success');
                            resolve();
                            return;
                        }
                        
                        // 未完成，继续轮询
                        attempts++;
                        
                        if (attempts >= maxAttempts) {
                            // 达到最大尝试次数
                            throw new Error('分析超时，请稍后查看结果');
                        }
                        
                        // 更新加载文本
                        const messageIndex = Math.min(Math.floor(attempts / 5), loadingMessages.length - 1);
                        document.getElementById('analysisLoadingText').textContent = '正在进行智能分析，请耐心等待...';
                        document.getElementById('analysisLoadingStatus').textContent = loadingMessages[messageIndex];
                        
                        // 显示进度更新
                        const progressPercentage = Math.min(90, Math.floor((attempts / maxAttempts) * 100));
                        const progressBar = document.querySelector('#analysisLoading .progress-bar');
                        progressBar.setAttribute('aria-valuenow', progressPercentage);
                        progressBar.style.width = `${progressPercentage}%`;
                        
                        // 继续轮询
                        setTimeout(checkResult, pollingInterval);
                        
                    } catch (error) {
                        console.error('轮询分析结果失败:', error);
                        
                        // 隐藏加载中，显示无结果
                        document.getElementById('analysisLoading').style.display = 'none';
                        document.getElementById('noAnalysisResult').style.display = 'block';
                        
                        // 重新启用按钮
                        const analyzeButtons = document.querySelectorAll('#analyzeProductBtn, #startAnalysisBtn');
                        analyzeButtons.forEach(btn => {
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-chart-bar"></i> 开始分析';
                        });
                        
                        showToast('分析失败', error.message, 'error');
                        reject(error);
                    }
                };
                
                // 开始第一次检查
                checkResult();
            });
        }
        
        // 更新分析状态
        function updateAnalysisStatus(hasAnalysis) {
            const statusBadge = hasAnalysis ? 
                '<span class="status-badge badge-success"><i class="fas fa-check-circle"></i> 已分析</span>' : 
                '<span class="status-badge badge-warning"><i class="fas fa-clock"></i> 未分析</span>';
                
            document.getElementById('analysisStatus').innerHTML = statusBadge;
            document.getElementById('analysisStatusStat').innerHTML = hasAnalysis ? 
                '<i class="fas fa-check-circle text-success"></i>' : 
                '<i class="fas fa-clock text-warning"></i>';
        }
        
        // 加载产品详情
        async function loadProductDetails() {
            try {
                const response = await fetch(`/api/products/${productId}`);
                
                if (!response.ok) {
                    throw new Error('获取产品详情失败');
                }
                
                productData = await response.json();
                
                // 更新产品信息
                document.getElementById('productName').textContent = productData.name;
                document.getElementById('productNameInfo').textContent = productData.name;
                document.getElementById('productDescription').textContent = `${productData.name} 商品竞品分析`;
                
                // 格式化日期
                const date = new Date(productData.created_time * 1000);
                const formattedDate = date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                const formattedTime = date.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit'
                });
                
                document.getElementById('productDate').textContent = `${formattedDate} ${formattedTime}`;
                document.getElementById('creationDateStat').textContent = formattedDate;
                
                // 更新图片数量
                document.getElementById('imageCount').textContent = `${productData.images.length} 张`;
                document.getElementById('imageCountStat').textContent = productData.images.length;
                
                // 更新分析状态
                updateAnalysisStatus(productData.analysis_result);
                
                if (productData.analysis_result) {
                    document.getElementById('analyzeProductBtn').innerHTML = '<i class="fas fa-chart-bar me-2"></i>重新分析';
                    document.getElementById('startAnalysisBtn').innerHTML = '<i class="fas fa-chart-bar me-2"></i>重新分析';
                }
                
                // 获取图片OCR状态
                let imageTexts = {};
                try {
                    const textsResponse = await fetch(`/api/products/${productId}/image-texts`);
                    if (textsResponse.ok) {
                        const imageTextsArray = await textsResponse.json();
                        // 转换为更易用的对象格式
                        imageTextsArray.forEach(item => {
                            if (item && item.image_name) {
                                imageTexts[item.image_name] = item.text_content || '';
                            }
                        });
                    }
                } catch (e) {
                    console.error("获取图片OCR内容失败:", e);
                    imageTexts = {};
                }
                
                // 更新图片列表
                const productImages = document.getElementById('productImages');
                productImages.innerHTML = '';
                
                if (productData.images.length === 0) {
                    document.getElementById('noImages').style.display = 'block';
                } else {
                    document.getElementById('noImages').style.display = 'none';
                    
                    productData.images.forEach(image => {
                        const imageUrl = `/static/uploads/products/${productId}/${image}`;
                        const hasText = imageTexts && imageTexts[image] && imageTexts[image].trim().length > 0;
                        
                        const imageItem = document.createElement('div');
                        imageItem.className = 'product-image-item';
                        imageItem.innerHTML = `
                            <a href="${imageUrl}" data-fancybox="gallery" data-caption="${productData.name} - ${image}">
                                <img src="${imageUrl}" alt="${image}" loading="lazy">
                            </a>
                            <div class="image-actions">
                                <button class="btn-image-action btn-image-extract" data-image="${image}">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="btn-image-action btn-image-delete" data-image="${image}">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                            <div class="image-status ${hasText ? 'has-text' : 'no-text'}">
                                ${hasText ? '内容已提取' : '内容未提取'}
                            </div>
                        `;
                        productImages.appendChild(imageItem);
                        
                        // 绑定删除事件
                        const deleteBtn = imageItem.querySelector('.btn-image-delete');
                        deleteBtn.addEventListener('click', function() {
                            deleteImage(this.getAttribute('data-image'));
                        });
                        
                        // 绑定提取事件
                        const extractBtn = imageItem.querySelector('.btn-image-extract');
                        extractBtn.addEventListener('click', function() {
                            extractImageText(this.getAttribute('data-image'));
                        });
                    });
                    
                    // 确保Fancybox已加载
                    if (typeof Fancybox !== 'undefined') {
                        // 初始化Fancybox (Fancybox 4.0版本写法)
                        Fancybox.bind('[data-fancybox="gallery"]', {
                            // 基本设置
                            loop: true,
                            // 工具栏按钮
                            Toolbar: {
                                display: [
                                    "zoom",
                                    "slideShow", 
                                    "fullScreen", 
                                    "download", 
                                    "thumbs", 
                                    "close"
                                ]
                            },
                            // 动画效果
                            Image: { zoom: true }
                        });
                        console.log("Fancybox 4.0 initialized");
                    } else {
                        console.error("Fancybox not loaded");
                    }
                }
                
                // 更新分析结果
                if (productData.analysis_result) {
                    document.getElementById('noAnalysisResult').style.display = 'none';
                    document.getElementById('analysisResult').style.display = 'block';
                    document.getElementById('analysisResult').innerHTML = formatAnalysisResult(productData.analysis_result);
                } else {
                    document.getElementById('noAnalysisResult').style.display = 'block';
                    document.getElementById('analysisResult').style.display = 'none';
                }
                
            } catch (error) {
                console.error('获取产品详情失败:', error);
                showToast('获取失败', '获取产品详情失败，请刷新页面重试', 'error');
            }
        }
        
        // 格式化分析结果，添加高亮
        function formatAnalysisResult(text) {
            if (!text) return "暂无分析结果";
            
            // 使用marked解析Markdown格式
            try {
                // 配置marked选项
                marked.setOptions({
                    breaks: true,       // 将换行符转换为<br>
                    gfm: true,          // 启用GitHub风格的Markdown
                    headerIds: true,    // 为标题添加ID
                    mangle: false       // 不转义HTML字符
                });
                
                // 解析Markdown
                let formattedHtml = marked.parse(text);
                
                // 高亮关键词
                const keywords = ['优势', '亮点', '特色', '竞争力', '突出', '强大', '领先', '创新', '独特', 
                                 '性能优越', '高效', '高质量', '高品质', '市场领导者', '技术先进'];
                keywords.forEach(keyword => {
                    const regex = new RegExp(`(${keyword})(?![^<]*>)`, 'g');
                    formattedHtml = formattedHtml.replace(regex, '<span class="highlight">$1</span>');
                });
                
                return formattedHtml;
            } catch (e) {
                console.error("Markdown解析错误:", e);
                
                // 如果解析失败，使用简单格式化
                // 预处理：分段落和标题
                let sections = text.split(/(?=\d+\.\s+)/);
                let formattedHtml = '';
                
                if (sections.length <= 1) {
                    // 如果没有标准的数字标题格式，使用简单格式化
                    formattedHtml = `<div class="analysis-block"><div class="analysis-content">${text}</div></div>`;
                } else {
                    sections.forEach(section => {
                        if (!section.trim()) return;
                        
                        // 提取标题和内容
                        const titleMatch = section.match(/^(\d+\.\s+[^\n]+)/);
                        if (titleMatch) {
                            const title = titleMatch[1];
                            const content = section.replace(title, '').trim();
                            
                            formattedHtml += `
                                <div class="analysis-section">
                                    <h5 class="mb-3">${title}</h5>
                                    <div class="analysis-content ps-3">${content}</div>
                                </div>
                            `;
                        } else {
                            formattedHtml += `<div class="analysis-content">${section}</div>`;
                        }
                    });
                }
                
                // 高亮关键词
                const keywords = ['优势', '亮点', '特色', '竞争力', '突出', '强大', '领先', '创新', '独特', 
                                 '性能优越', '高效', '高质量', '高品质', '市场领导者', '技术先进'];
                keywords.forEach(keyword => {
                    const regex = new RegExp(`(${keyword})`, 'g');
                    formattedHtml = formattedHtml.replace(regex, '<span class="highlight">$1</span>');
                });
                
                return formattedHtml;
            }
        }

        // 处理图片删除
        async function deleteImage(imageName) {
            try {
                // 显示确认对话框
                const confirmed = await showConfirmDialog(
                    "删除图片", 
                    `确定要删除图片 "${imageName}" 吗？此操作不可撤销。`
                );
                
                if (!confirmed) return false;
                
                // 发送删除请求
                const response = await fetch(`/api/products/${productId}/images/${imageName}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    console.log("删除成功:", result);
                    
                    // 重新加载产品详情
                    await loadProductDetails();
                    return true;
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || "删除失败");
                }
            } catch (error) {
                console.error("删除图片失败:", error);
                alert(`删除图片失败: ${error.message}`);
                return false;
            }
        }

        // 确认对话框
        function showConfirmDialog(title, message) {
            return new Promise((resolve) => {
                // 创建对话框元素
                const dialog = document.createElement('div');
                dialog.className = 'confirm-dialog';
                dialog.innerHTML = `
                    <div class="confirm-dialog-content">
                        <div class="confirm-dialog-title">${title}</div>
                        <div class="confirm-dialog-message">${message}</div>
                        <div class="confirm-dialog-actions">
                            <button class="btn btn-secondary btn-cancel">取消</button>
                            <button class="btn btn-danger btn-confirm">删除</button>
                        </div>
                    </div>
                `;
                
                // 添加到body
                document.body.appendChild(dialog);
                
                // 动画效果
                setTimeout(() => dialog.classList.add('show'), 10);
                
                // 绑定事件
                const confirmBtn = dialog.querySelector('.btn-confirm');
                const cancelBtn = dialog.querySelector('.btn-cancel');
                
                confirmBtn.addEventListener('click', () => {
                    dialog.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(dialog);
                        resolve(true);
                    }, 300);
                });
                
                cancelBtn.addEventListener('click', () => {
                    dialog.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(dialog);
                        resolve(false);
                    }, 300);
                });
            });
        }

        // 重新提取图片内容
        async function extractImageText(imageName) {
            try {
                // 获取图片元素
                const imageElement = document.querySelector(`[data-image="${imageName}"]`).closest('.product-image-item');
                
                // 显示提取中状态
                const progressBar = document.createElement('div');
                progressBar.className = 'extract-progress active';
                imageElement.appendChild(progressBar);
                
                // 修改按钮样式
                const extractBtn = imageElement.querySelector('.btn-image-extract');
                const originalHTML = extractBtn.innerHTML;
                extractBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                extractBtn.disabled = true;
                
                // 发送请求
                const response = await fetch(`/api/products/${productId}/images/${imageName}/extract`, {
                    method: 'POST'
                });
                
                // 移除提取中状态
                if (progressBar) {
                    progressBar.classList.remove('active');
                    setTimeout(() => {
                        imageElement.removeChild(progressBar);
                    }, 300);
                }
                
                // 还原按钮样式
                extractBtn.innerHTML = originalHTML;
                extractBtn.disabled = false;
                
                if (response.ok) {
                    const result = await response.json();
                    console.log("提取成功:", result);
                    
                    // 更新图片状态
                    const statusElement = imageElement.querySelector('.image-status');
                    if (statusElement) {
                        statusElement.textContent = '内容已提取';
                        statusElement.className = 'image-status has-text';
                    }
                    
                    // 提示用户
                    showToast('提取成功', '图片内容已成功提取', 'success');
                    return true;
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || "提取失败");
                }
            } catch (error) {
                console.error("提取图片内容失败:", error);
                showToast('提取失败', error.message || '提取图片内容失败', 'error');
                return false;
            }
        }

        // 添加提示消息功能
        function showToast(title, message, type = 'info') {
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `toast-notification toast-${type}`;
            
            // 设置内容
            toast.innerHTML = `
                <div class="toast-icon">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                </div>
                <div class="toast-content">
                    <div class="toast-title">${title}</div>
                    <div class="toast-message">${message}</div>
                </div>
                <button class="toast-close"><i class="fas fa-times"></i></button>
            `;
            
            // 添加到页面
            document.body.appendChild(toast);
            
            // 显示动画
            setTimeout(() => {
                toast.classList.add('show');
            }, 10);
            
            // 绑定关闭事件
            const closeBtn = toast.querySelector('.toast-close');
            closeBtn.addEventListener('click', () => {
                toast.classList.remove('show');
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            });
            
            // 自动关闭
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => {
                    if (document.body.contains(toast)) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 5000);
        }

        // 文件上传处理
        document.getElementById('uploadForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const files = document.getElementById('fileInput').files;
            if (files.length === 0) {
                alert('请选择要上传的文件');
                return;
            }
            
            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('files', files[i]);
            }
            
            try {
                const response = await fetch(`/api/products/${productId}/files`, {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error('上传失败');
                }
                
                const result = await response.json();
                alert(result.message);
                loadFiles();
            } catch (error) {
                alert('上传失败: ' + error.message);
            }
        });

        // 加载文件列表
        async function loadFiles() {
            try {
                const response = await fetch(`/api/products/${productId}/files`);
                if (!response.ok) {
                    throw new Error('获取文件列表失败');
                }
                
                const files = await response.json();
                const fileList = document.getElementById('fileList');
                fileList.innerHTML = '';
                
                files.forEach(file => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${file.name}</td>
                        <td>${file.type}</td>
                        <td>${formatFileSize(file.size)}</td>
                        <td>${new Date(file.created_at).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary view-file" data-file-id="${file.id}">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger delete-file" data-file-id="${file.id}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    `;
                    fileList.appendChild(row);
                });
                
                // 添加查看文件事件
                document.querySelectorAll('.view-file').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const fileId = this.getAttribute('data-file-id');
                        viewFile(fileId);
                    });
                });
                
                // 添加删除文件事件
                document.querySelectorAll('.delete-file').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const fileId = this.getAttribute('data-file-id');
                        deleteFile(fileId);
                    });
                });
            } catch (error) {
                console.error('Error:', error);
                alert('加载文件列表失败: ' + error.message);
            }
        }

        // 查看文件
        async function viewFile(fileId) {
            try {
                const response = await fetch(`/api/products/${productId}/files/${fileId}/content`);
                if (!response.ok) {
                    throw new Error('获取文件失败');
                }
                
                const file = await response.json();
                const fileType = file.type.toLowerCase();
                
                // 根据文件类型选择预览方式
                if (fileType.startsWith('image/')) {
                    showImagePreview(`/static/uploads/products/${productId}/${fileId}`);
                } else if (fileType === 'application/pdf') {
                    showPdfPreview(`/static/uploads/products/${productId}/${fileId}`);
                } else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                    showDocxPreview(`/static/uploads/products/${productId}/${fileId}`);
                } else if (fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                    showExcelPreview(`/static/uploads/products/${productId}/${fileId}`);
                } else if (fileType.startsWith('text/')) {
                    // 获取文本内容
                    const textResponse = await fetch(`/static/uploads/products/${productId}/${fileId}`);
                    const text = await textResponse.text();
                    showTextContent(text);
                } else {
                    // 对于不支持预览的文件类型，提供下载选项
                    window.open(`/static/uploads/products/${productId}/${fileId}`, '_blank');
                }
            } catch (error) {
                console.error('查看文件失败:', error);
                alert('查看文件失败: ' + error.message);
            }
        }

        // 删除文件
        async function deleteFile(fileId) {
            if (!confirm('确定要删除这个文件吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/products/${productId}/files/${fileId}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error('删除失败');
                }
                
                alert('文件删除成功');
                loadFiles();
            } catch (error) {
                alert('删除失败: ' + error.message);
            }
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 页面加载时加载文件列表
        document.addEventListener('DOMContentLoaded', function() {
            loadFiles();
            
            // 添加刷新按钮事件
            document.getElementById('refreshFiles').addEventListener('click', function() {
                loadFiles();
            });
        });

        // 显示图片预览
        function showImagePreview(path) {
            const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
            const imagePreview = document.getElementById('imagePreview');
            const img = imagePreview.querySelector('img');
            
            // 隐藏其他预览
            document.querySelectorAll('.modal-body > div').forEach(el => el.classList.add('d-none'));
            
            // 显示图片预览
            img.src = path;
            imagePreview.classList.remove('d-none');
            modal.show();
        }

        // 显示PDF预览
        function showPdfPreview(path) {
            const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
            const pdfPreview = document.getElementById('pdfPreview');
            const iframe = pdfPreview.querySelector('iframe');
            
            // 隐藏其他预览
            document.querySelectorAll('.modal-body > div').forEach(el => el.classList.add('d-none'));
            
            // 显示PDF预览
            iframe.src = path;
            pdfPreview.classList.remove('d-none');
            modal.show();
        }

        // 显示Word文档预览
        function showDocxPreview(path) {
            const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
            const docxPreview = document.getElementById('docxPreview');
            const content = docxPreview.querySelector('.docx-content');
            
            // 隐藏其他预览
            document.querySelectorAll('.modal-body > div').forEach(el => el.classList.add('d-none'));
            
            // 显示Word文档预览
            content.innerHTML = '<p>正在加载Word文档内容...</p>';
            docxPreview.classList.remove('d-none');
            modal.show();
            
            // 加载Word文档内容
            fetch(path)
                .then(response => response.text())
                .then(html => {
                    content.innerHTML = html;
                })
                .catch(error => {
                    content.innerHTML = '<p class="text-danger">加载Word文档失败</p>';
                });
        }

        // 显示Excel预览
        function showExcelPreview(path) {
            const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
            const excelPreview = document.getElementById('excelPreview');
            const content = document.getElementById('excelContent');
            
            // 隐藏其他预览
            document.querySelectorAll('.modal-body > div').forEach(el => el.classList.add('d-none'));
            
            // 显示Excel预览
            content.innerHTML = '<tr><td colspan="100">正在加载Excel内容...</td></tr>';
            excelPreview.classList.remove('d-none');
            modal.show();
            
            // 加载Excel内容
            fetch(path)
                .then(response => response.json())
                .then(data => {
                    content.innerHTML = '';
                    data.forEach(row => {
                        const tr = document.createElement('tr');
                        row.forEach(cell => {
                            const td = document.createElement('td');
                            td.textContent = cell;
                            tr.appendChild(td);
                        });
                        content.appendChild(tr);
                    });
                })
                .catch(error => {
                    content.innerHTML = '<tr><td colspan="100" class="text-danger">加载Excel失败</td></tr>';
                });
        }

        // 显示文本内容
        function showTextContent(text) {
            const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
            const textPreview = document.getElementById('textPreview');
            const content = textPreview.querySelector('.text-content');
            
            // 隐藏其他预览
            document.querySelectorAll('.modal-body > div').forEach(el => el.classList.add('d-none'));
            
            // 显示文本内容
            content.textContent = text;
            textPreview.classList.remove('d-none');
            modal.show();
        }
    </script>

    <!-- 确认删除对话框模板 (初始不显示) -->
    <div id="confirmDialog" class="confirm-dialog">
        <div class="confirm-dialog-content">
            <div class="confirm-dialog-title" id="confirmDialogTitle">删除确认</div>
            <div class="confirm-dialog-message" id="confirmDialogMessage">确定要执行此操作吗？</div>
            <div class="confirm-dialog-actions">
                <button class="btn btn-secondary" id="confirmDialogCancel">取消</button>
                <button class="btn btn-danger" id="confirmDialogConfirm">删除</button>
            </div>
        </div>
    </div>

    <!-- 添加上传进度容器 -->
    <div class="upload-progress-container" id="uploadProgressContainer"></div>
</body>
</html> 